package com.cqndt.disaster.device.service.data.impl;

import com.cqndt.disaster.device.dao.data.*;
import com.cqndt.disaster.device.entity.data.TabWarningDevice;
import com.cqndt.disaster.device.service.data.TabWarningUniteService;
import com.cqndt.disaster.device.sys.vo.SysUserVo;
import com.cqndt.disaster.device.util.AbstractController;
import com.cqndt.disaster.device.util.JSONUtils;
import com.cqndt.disaster.device.util.Result;
import com.cqndt.disaster.device.vo.data.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.crypto.hash.Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.*;

@Service
public class TabWarningUniteServiceImpl extends AbstractController implements TabWarningUniteService {

    @Autowired
    private TabWarningUniteMapper tabWarningUniteMapper;

    @Autowired
    private TabWarningDeviceMapper tabWarningDeviceMapper;
    @Autowired
    private TabDeviceMapper tabDeviceMapper;


    /**
     * 联合预警列表
     *
     * @param vo
     * @return
     */
    @Override
    public Result selectList(TabWarningUniteVo vo) {
        PageHelper.startPage(vo.getPage(), vo.getLimit());
        PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(tabWarningUniteMapper.selectList(vo));
        Result result = new Result();
        result.setCount((int) pageInfo.getTotal());
        result.setData(pageInfo.getList());
        return result;
    }

    /**
     * 新增联合预警及其预警设备
     *
     * @param vo
     * @return
     */
    @Override
    @Transactional(rollbackFor = {Exception.class, Error.class})
    public Result save(TabjieshouVo vo) {
        //String aaa="/(^[\\-0-9][0-9]*(.[0-9]+)?)$/";
        if (StringUtils.isEmpty(vo.getBase().get("name"))) {
            return new Result().failure(-1, "请输入综合告警名称");
        } else if (StringUtils.isEmpty(vo.getBase().get("redWarning"))) {
            return new Result().failure(-1, "请输入红色告警短信模版");
        } else if (StringUtils.isEmpty(vo.getBase().get("orangeWarning"))) {
            return new Result().failure(-1, "请输入橙色告警短信模版");
        } else if (StringUtils.isEmpty(vo.getBase().get("yellowWarning"))) {
            return new Result().failure(-1, "请输入黄色告警短信模版");
        } else if (StringUtils.isEmpty(vo.getBase().get("blueWarning"))) {
            return new Result().failure(-1, "请输入蓝色告警短信模版");
        }
        for (Map map :vo.getThres()){
            if ("[]".equals( map.get("marks").toString()) || map.get("marks") == null ){
                return new Result().failure(-1,"操作失败");
            }
            List<Map<String, Object>> list = (List<Map<String, Object>>) map.get("marks");
            for (Map map1 :list){
                if (StringUtils.isEmpty(map1.get("red").toString())){
                    return new Result().failure(-1,"请正确输入红色预警阈值");
                }else if (StringUtils.isEmpty(map1.get("orange").toString())){
                    return new Result().failure(-1,"请正确输入橙色预警阈值");
                }else if (StringUtils.isEmpty(map1.get("yellow").toString())){
                    return new Result().failure(-1,"请正确输入黄色预警阈值");
                }else if (StringUtils.isEmpty(map1.get("blue").toString())){
                    return new Result().failure(-1,"请正确输入蓝色预警阈值");
                }
            }
        }

        //新建联合告警实体类
        TabWarningUniteVo vo1 = new TabWarningUniteVo();
        //新建预警设备实体类
        TabWarningDevice vo2 = null;
        //获取用户名
        SysUserVo user = getUser();
        String userName = user.getUserName();
        vo1.setCreatePerson(userName);
        //获取时间
        Date date = new Date();
        vo1.setCreateTime(date);

        //联合告警实体类设置值
        vo1.setName(vo.getBase().get("name"));
        vo1.setIsAvailable(Integer.parseInt(vo.getBase().get("isAvailable")));
        vo1.setRedWarning(vo.getBase().get("redWarning"));
        vo1.setOrangeWarning(vo.getBase().get("orangeWarning"));
        vo1.setYellowWarning(vo.getBase().get("yellowWarning"));
        vo1.setBlueWarning(vo.getBase().get("blueWarning"));
        int countId = tabWarningUniteMapper.countId();
        int maxId = 0;
        if (countId == 0) {
            maxId = 1;
        } else {
            maxId = tabWarningUniteMapper.getMaxId();
        }
        vo1.setId(maxId + 1);
        int save = tabWarningUniteMapper.save(vo1);
        //获取联合告警表最大id
        int maxId1 = tabWarningUniteMapper.getMaxId();
        //循环添加进预警设备实体类
        for (Map map : vo.getThres()) {
            List<Map<String, Object>> list = (List<Map<String, Object>>) map.get("marks");
            for (Map map1 : list) {
                vo2 = new TabWarningDevice();
                vo2.setCreateTime(date);
                vo2.setIdentify((String) map1.get("mark"));
                vo2.setIdentifyName((String) map1.get("markName"));
                vo2.setLevel1(Double.valueOf(map1.get("red").toString()));
                vo2.setLevel2(Double.valueOf(map1.get("orange").toString()));
                vo2.setLevel3(Double.valueOf(map1.get("yellow").toString()));
                vo2.setLevel4(Double.valueOf(map1.get("blue").toString()));
                vo2.setDeviceNo(map.get("id").toString());
                vo2.setProjectNo(map.get("pid").toString());
                vo2.setDeviceType(Integer.parseInt(map.get("deviceType").toString()));
                vo2.setWarningUniteId(maxId1);
                vo2.setSequence((int) map1.get("sequence"));
                int i = tabWarningDeviceMapper.addWarningDevice(vo2);
            }
        }

        Result result = new Result();
        result.setCode(0);
        result.setData(save);
        result.setMsg("添加成功");
        return result;
    }

    /**
     * 修改联合预警及其预警设备
     *
     * @param vo
     * @return
     */
    @Override
    @Transactional(rollbackFor = {Exception.class, Error.class})
    public Result update(TabjieshouVo vo) {

        if (StringUtils.isEmpty(vo.getBase().get("name"))) {
            return new Result().failure(-1, "请输入综合告警名称");
        } else if (StringUtils.isEmpty(vo.getBase().get("redWarning"))) {
            return new Result().failure(-1, "请输入红色告警短信模版");
        } else if (StringUtils.isEmpty(vo.getBase().get("orangeWarning"))) {
            return new Result().failure(-1, "请输入橙色告警短信模版");
        } else if (StringUtils.isEmpty(vo.getBase().get("yellowWarning"))) {
            return new Result().failure(-1, "请输入黄色告警短信模版");
        } else if (StringUtils.isEmpty(vo.getBase().get("blueWarning"))) {
            return new Result().failure(-1, "请输入蓝色告警短信模版");
        }

        for (Map map :vo.getThres()){
            if ("[]".equals( map.get("marks").toString()) ){
                return new Result().failure(-1,"操作失败");
            }
            List<Map<String, Object>> list = (List<Map<String, Object>>) map.get("marks");
            for (Map map1 :list){
                if (StringUtils.isEmpty(map1.get("level1").toString())){
                    return new Result().failure(-1,"请正确输入红色预警阈值");
                }else if (StringUtils.isEmpty(map1.get("level2").toString())){
                    return new Result().failure(-1,"请正确输入橙色预警阈值");
                }else if (StringUtils.isEmpty(map1.get("level3").toString())){
                    return new Result().failure(-1,"请正确输入黄色预警阈值");
                }else if (StringUtils.isEmpty(map1.get("level4").toString())){
                    return new Result().failure(-1,"请正确输入蓝色预警阈值");
                }
            }
        }

        //新建联合告警实体类
        TabWarningUniteVo vo1 = new TabWarningUniteVo();
        //新建预警设备实体类
        TabWarningDevice vo2 = null;
        //获取用户名
        SysUserVo user = getUser();
        String userName = user.getUserName();
        vo1.setUpdatePerson(userName);
        //获取时间
        Date date = new Date();
        vo1.setUpdateTime(date);

        //联合告警实体类设置值
        int id = Integer.parseInt(vo.getBase().get("id"));
        vo1.setId(id);
        vo1.setName(vo.getBase().get("name"));
        vo1.setIsAvailable(Integer.parseInt(vo.getBase().get("isAvailable")));
        vo1.setRedWarning(vo.getBase().get("redWarning"));
        vo1.setOrangeWarning(vo.getBase().get("orangeWarning"));
        vo1.setYellowWarning(vo.getBase().get("yellowWarning"));
        vo1.setBlueWarning(vo.getBase().get("blueWarning"));
        int update = tabWarningUniteMapper.update(vo1);
        //根据联合预警表id获取每一个已有设备id （分组展示）
        List<TabWarningDevice> deviceNoGroup = tabWarningDeviceMapper.getDeviceNoGroup(id);

        //循环添加进预警设备实体类，对已有的设备阈值进行修改
        for (Map map : vo.getThres()) {
            List<Map<String, Object>> markList = (List<Map<String, Object>>) map.get("marks");
            for (TabWarningDevice tabWarningDevice : deviceNoGroup) {
                for (Map map1 : markList) {
                    if (tabWarningDevice.getDeviceNo().equals(map.get("id").toString())) {
                        vo2 = new TabWarningDevice();
                        vo2.setUpdateTime(date);
                        vo2.setDeviceNo(map.get("id").toString());
                        vo2.setProjectNo(map.get("pid").toString());
                        vo2.setLevel1(Double.valueOf(map1.get("level1").toString()));
                        vo2.setLevel2(Double.valueOf(map1.get("level2").toString()));
                        vo2.setLevel3(Double.valueOf(map1.get("level3").toString()));
                        vo2.setLevel4(Double.valueOf(map1.get("level4").toString()));
                        vo2.setIdentify((String) map1.get("identify"));
                        vo2.setIdentifyName((String) map1.get("identifyName"));
                        vo2.setWarningUniteId(id);
                        vo2.setSequence((int) map1.get("sequence"));
                        int i = tabWarningDeviceMapper.updateWarningDevice(vo2);
                    }
                }
            }
        }
        //所有传回来的数据设备id集合
        List<Integer> allDeviceList = new ArrayList<>();
        //新增加的设备id集合
        List<Integer> newDeviceList = new ArrayList<>();
        //需要删除的设备id集合
        List<Integer> deleteDeviceList = new ArrayList<>();

        //获取之前所有有的设备
        for (Map map : vo.getThres()) {
            allDeviceList.add(Integer.parseInt(map.get("id").toString()));
        }
        //传回的设备id和已经有的设备id进行对比
        for (Integer s : allDeviceList) {
            int count = 0;
            for (TabWarningDevice tabWarningDevice : deviceNoGroup) {
                if (Integer.parseInt(tabWarningDevice.getDeviceNo()) == s) {
                    break;
                }
                count++;
                if (count == deviceNoGroup.size()) {
                    //把不重复的数据存入
                    newDeviceList.add(s);
                }
            }
        }
        System.out.println(newDeviceList);

        for (TabWarningDevice tabWarningDevice : deviceNoGroup) {//循环拥有的每一个设备
            int count = 0;
            for (Integer s : allDeviceList) {
                if (Integer.parseInt(tabWarningDevice.getDeviceNo()) == s) {
                    break;
                }
                count++;
                if (count == allDeviceList.size()) {
                    //把需要删除的数据存入
                    deleteDeviceList.add(Integer.parseInt(tabWarningDevice.getDeviceNo()));
                }
            }
        }
        System.out.println(deleteDeviceList);
        for (Integer delete : deleteDeviceList) {
            tabWarningDeviceMapper.deleteDeviceByDeviceNo(delete, Integer.parseInt(vo.getBase().get("id")));
        }

        for (Map map : vo.getThres()) {
            List<Map<String, Object>> markList = (List<Map<String, Object>>) map.get("marks");
            for (Integer ii : newDeviceList) {
                for (Map map1 : markList) {
                    if (ii.toString().equals(map.get("id").toString())) {
                        vo2 = new TabWarningDevice();
                        vo2.setDeviceNo(ii.toString());
                        vo2.setProjectNo(map.get("pid").toString());
                        vo2.setCreateTime(date);
                        vo2.setUpdateTime(date);
                        vo2.setDeviceType(Integer.parseInt(map.get("deviceType").toString()));
                        vo2.setLevel1(Double.valueOf(map1.get("level1").toString()));
                        vo2.setLevel2(Double.valueOf(map1.get("level2").toString()));
                        vo2.setLevel3(Double.valueOf(map1.get("level3").toString()));
                        vo2.setLevel4(Double.valueOf(map1.get("level4").toString()));
                        vo2.setIdentify((String) map1.get("identify"));
                        vo2.setIdentifyName((String) map1.get("identifyName"));
                        vo2.setSequence((int) map1.get("sequence"));
                        vo2.setWarningUniteId(id);
                        tabWarningDeviceMapper.addWarningDevice(vo2);
                    }
                }
            }
        }


        Result result = new Result();
        result.setCode(0);
        result.setData(update);
        result.setMsg("修改成功");
        return result;
    }

    @Override
    public Result delete(String id) {
        if (null == id) {
            return new Result().failure(-1, "请选择至少一条数据进行操作");
        }
        String[] ids = id.split(",");
        for (String idStr : ids) {
            tabWarningUniteMapper.delete(Integer.parseInt(idStr));
            tabWarningDeviceMapper.deleteWarningDevice(Integer.parseInt(idStr));
        }
        return new Result().success("删除成功");
    }

    //回显至选中设备填写阈值
    @Override
    public Result getCheck(TabjieshouVo vo) {
        int id = vo.getId();
        List<TabjsVo> check = tabWarningDeviceMapper.getCheck(id);

        for (TabjsVo tab : check) {

            List<TabjsVo> deviceByDeviceNo = tabDeviceMapper.getDeviceByDeviceNo(Integer.parseInt(tab.getProjectNo()), id);

            tab.setChildren(deviceByDeviceNo);

            deviceByDeviceNo.forEach(device -> {
                device.setPid("p"+tab.getProjectNo());
                List<TabWarningDevice> serson = tabWarningDeviceMapper.getSerson(device.getDeviceNo(), id);
                device.setMarks(serson);
            });

        }
        Result result = new Result();
        result.setData(check);
        return result;
    }


    @Override
    public Result reciveDevice(TabJHouVo vo) throws Exception {

        // 联合告警id
        Integer uniteId = Integer.parseInt(vo.getAid().toString());

        //所有项目及其下所有信息
        List<Map<String, Object>> deviceList = vo.getAllN();

        // 所有传过来设备ID
        List<String> deviceNoList = new ArrayList<>();

        //遍历获取所有项目下设备id
        for (Map<String, Object> deviceMap : deviceList) {
            List<Map<String, Object>> deviceTempList = (List<Map<String, Object>>) deviceMap.get("children");
            deviceMap.get("label");
            for (Map<String, Object> tempMap : deviceTempList) {
                deviceNoList.add(tempMap.get("id").toString());
            }
        }

        // 查出当前联合告警下拥有的设备
        List<TabWarningDevice> warnDeviceList = tabWarningDeviceMapper.getDeviceByWarn(uniteId);

        // 返回的数据结构
        List<Map<String, Object>> thresList = new ArrayList<>();

        // 不存在的设备
        List<String> noExitList = new ArrayList<>();

        // 查得到的设备数据
        for (String device : deviceNoList) {
            Map<String, Object> zxc = new HashMap<>();
            List<Map<String, Object>> name = tabDeviceMapper.getDeviceTypeByDeviceName(Integer.parseInt(device));

            for (Map map : name) {
                if (map.get("id").toString().equals(device)) { //device为查得到的设备id
                    zxc.put("label", map.get("label"));
                    zxc.put("pid", map.get("pid"));
                    zxc.put("deviceType", map.get("deviceType"));
                }
            }
            // 判断是否存在设备
            boolean isExit = true;
            Map<String, Object> resultMap = new HashMap<>();

            List<TabWarningDevice> marksList = new ArrayList<>();
            for (TabWarningDevice tabWarningDevice : warnDeviceList) {
                if (tabWarningDevice.getDeviceNo().equals(device)) {
                    marksList.add(tabWarningDevice);
                    isExit = false;
                }
            }

            if (isExit) {
                noExitList.add(device);
            } else {

                resultMap.put("id", device);
                resultMap.put("marks", marksList);
                resultMap.put("label", zxc.get("label"));
                resultMap.put("pid", zxc.get("pid"));
                resultMap.put("deviceType", zxc.get("deviceType"));
                thresList.add(resultMap);
            }
        }

        Map<String, Object> resultMap1;
        for (String noexitList : noExitList) {
            resultMap1 = new HashMap<>();
            resultMap1.put("id", noexitList);
            //查询出新增加的设备名称 label、类型 deviceType、父级和项目id pid
            Map<String, Object> zxc = tabDeviceMapper.getDeviceTypeByDeviceNameGroup(Integer.parseInt(resultMap1.get("id").toString()));
            //根据设备类型查询设备对应的模版
            List<TabWarningDevice> tabDeviceTemplateByDeviceValue = tabWarningDeviceMapper.getTabDeviceTemplateByDeviceValue1(Integer.parseInt(zxc.get("deviceType").toString()));
            resultMap1.put("marks", tabDeviceTemplateByDeviceValue);
            resultMap1.put("label", zxc.get("label"));
            resultMap1.put("deviceType", zxc.get("deviceType"));
            resultMap1.put("pid", zxc.get("pid"));
            thresList.add(resultMap1);
        }

        Result result = new Result();
        result.setData(thresList);
        return result;
    }


}
